package cn.zwx.security.example.utils;

import cn.zwx.security.example.config.JWTConfig;
import cn.zwx.security.example.entity.extend.SelfUserEntity;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description: JWT token 生成
 * @projectName:spring-boot-security-example
 * @see:cn.zwx.security.example.utils
 * @author:zhangwenxue
 * @createTime:2021/6/23 15:49
 * @version:1.0
 */
@Component
public class JWTTokenUtil {

    @Autowired
    private JWTConfig jwtConfig;


    /**
   * @description  生成Token
   * @return java.lang.String
   * @author zhangwenxue
   * @createTime 2021/6/23 15:55
   **/
    public String createAccessToken(SelfUserEntity selfUserEntity){
        // 登陆成功生成JWT
        String token = Jwts.builder()
                // 放入用户名和用户ID
                .setId(selfUserEntity.getUserId()+"")
                // 主题
                .setSubject(selfUserEntity.getUsername())
                // 签发时间
                .setIssuedAt(new Date())
                // 签发者
                .setIssuer("platform_web")
                // 自定义属性 放入用户拥有权限
                .claim("authorities", JSON.toJSONString(selfUserEntity.getAuthorities()))
                // 失效时间
                .setExpiration(new Date(System.currentTimeMillis() + jwtConfig.getExpiration()))
//                .setPayload()
                // 签名算法和密钥
                .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret())
                .compact();
        return token;
    }
}
